<template>
  <basic-container>
    <el-tabs v-model="activeName" style="margin: 0 10px" @tab-click="handleClick">
      <el-tab-pane label="物料类别" name="materialCategory"></el-tab-pane>
      <el-tab-pane label="物料数据" name="materialData"></el-tab-pane>
    </el-tabs>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :search.sync="query"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot-scope="{ row }" slot="rulesContentForm">
        <h3>规则配置:</h3>
        <rule-content ref="ruleContent" :rule-type="ruleType" :rule-data="rulesList" :dialog-type="dialogType" @queryPart="queryPart"></rule-content>
      </template>
      <template slot-scope="{}" slot="tableContentForm">
        <h3>{{ activeName === 'materialCategory' ? '物料类别配置:' : '物料数据配置:' }}</h3>
        <transfertable ref="transfertable" :type="activeName"></transfertable>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" @click="handleBatchAdd" v-if="permission.businessRules_add">批量配置规则 </el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
    </avue-crud>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import { catagoryData, getDicData, marterialData } from '@/views/warehouse/productrefactor/materialColumn';
import ruleContent from '@/views/warehouse/components/ruleContent';
import transfertable from '@/views/warehouse/components/transfertable';
import { batchSave, getMaterialCategoryList, getMaterialList, getRules, saveOrUpdate } from '@/api/warehouse/materialRules';
import { getList } from '@/api/warehouse/businessRules';

export default {
  name: 'materialRules', // 会渲染成传入的componentName
  components: {
    userTableConfig,
    ruleContent,
    transfertable
  },
  mixins: [userConfig()],
  data() {
    return {
      activeName: 'materialCategory',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      dialogType: 'batch',
      rulesList: [],
      ruleType: '',
      selectionList: [],
      data: [],
      option: {
        calcHeight: 30,
        labelWidth: 150,
        height: 'calc(100vh - 460px)',
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        searchMenuPosition: 'right',
        searchSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        editBtn: true,
        editBtnText: '规则配置',
        delBtn: false,
        addBtn: false,
        // addBtnText: '批量配置规则',
        indexLabel: '序号',
        columnBtn: false,
        column: catagoryData
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
    this.activeName = 'materialCategory';
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission, false),
        viewBtn: this.vaildData(this.permission, false),
        delBtn: this.vaildData(this.permission, false),
        editBtn: this.vaildData(this.permission, false)
      };
    },
    ids() {
      return this.selectionList.map((item) => item.id).join(',');
    }
  },
  methods: {
    async rowSave(row, done, loading) {
      try {
        const formData = this.$refs.ruleContent.formData;
        const selectData = this.$refs.transfertable.selectionList;
        let params = {};
        //规则配置表单 校验
        if (formData.length && !formData[0].name) {
          this.$message.warning('请进行规则配置');
          loading();
          return;
        }
        if (!selectData.length) {
          const selectType = this.activeName === 'materialCategory' ? '物料类别配置:' : ' :';
          this.$message.warning(`请选择${selectType}`);
          loading();
          return;
        }
        if (this.dialogType === 'batch') {
          const ruleRelationObjectDTO = selectData.map((item) => {
            return {
              type: this.activeName === 'materialCategory' ? 'mes_part_category' : 'mes_part_master',
              code: this.activeName === 'materialCategory' ? item.code : item.partNo,
              id: item.id,
              name: item.name
            };
          });
          const ruleSchemeBaseInfoBeans = formData.map((item) => {
            return {
              type: item.type,
              code: item.code,
              id: item.id,
              name: item.name
            };
          });
          params = { ruleRelationObjectDTO, ruleSchemeBaseInfoBeans };
        }
        const res = await batchSave(params);
        this.onLoad(this.page, this.query);
        this.$message.success('规则配置成功');
        done();
      } catch (e) {
        console.warn(e);
        loading();
      } finally {
      }
    },
    async rowUpdate(row, index, done, loading) {
      try {
        const formData = this.$refs.ruleContent.formData;
        if (formData.length && !formData.every((item) => item.name)) {
          this.$message.warning('存在未配置的规则，请检查测配置');
          loading();
          return;
        }
        const ruleSchemeBaseInfoBeans = formData.map((item) => {
          return {
            type: item.type,
            code: item.code,
            id: item.id,
            name: item.name
          };
        });
        const params = {
          objectType: this.activeName === 'materialCategory' ? 'mes_part_category' : 'mes_part_master',
          ruleSchemeBaseInfoBeans,
          code: this.form.code,
          id: this.form.id,
          name: this.form.name,
          type: this.form.type
        };
        const res = await saveOrUpdate(params);
        this.$message.success('规则配置成功');
        done();
        this.onLoad(this.page, this.query);
      } catch (e) {
        console.warn(e);
        loading();
      } finally {
        this.loading = false;
      }
    },
    rowDel(row) {},
    async beforeOpen(done, type) {
      const params = { partId: this.activeName === 'materialCategory' ? this.form.partCategoryId : this.form.partMasterId };
      if (['edit', 'view'].includes(type)) {
        this.dialogType = type;
        //  编辑下去除表格
        const delIndex = this.option.column.findIndex((item) => item.prop === 'tableContent');
        if (delIndex !== -1) {
          this.option.column.splice(delIndex, 1);
        }
        const res = await getRules(params);
        let catagoryObj = {};
        if (type === 'view') {
          catagoryObj.partCategoryCode = this.form.partCategoryCode || '';
          catagoryObj.partCategoryName = this.form.partCategoryName || '';
        }
        if (res.data.data && res.data.data.relationObject) {
          const relationObject = res.data.data && res.data.data.relationObject;
          this.form = Object.assign(relationObject, catagoryObj);
        } else {
          this.form = {
            ...catagoryObj,
            name: this.activeName === 'materialCategory' ? this.form.partCategoryName : this.form.partMasterName,
            code: this.activeName === 'materialCategory' ? this.form.partCategoryCode : this.form.partMasterCode,
            id: this.activeName === 'materialCategory' ? this.form.partCategoryId : this.form.partMasterId,
            type: this.activeName === 'materialCategory' ? 'mes_part_category' : 'mes_part_master'
          };
        }
        this.rulesList = (res.data.data && res.data.data.ruleSchemeList) || [];
      } else {
        this.rulesList = [];
      }

      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    handleDelete() {},
    handleBatchAdd() {
      const delIndex = this.option.column.findIndex((item) => item.prop === 'tableContent');
      if (delIndex === -1) {
        this.option.column.push({ label: '', prop: 'tableContent', formslot: true, labelWidth: 0, span: 24 });
      }
      this.dialogType = 'batch';
      this.$refs.crud.rowAdd();
    },
    handleConfigRules() {
      const delIndex = this.option.column.findIndex((item) => item.prop === 'tableContent');
      if (delIndex !== -1) {
        this.option.column.splice(delIndex, 1);
      }
      this.$refs.crud.rowEdit();
    },
    handleClick() {
      this.activeName === 'materialCategory' ? this.$set(this.option, 'column', catagoryData) : this.$set(this.option, 'column', marterialData);
      this.onLoad(this.page);
      // console.log(this.$refs.crud);
      // const column = this.findObject(this.option.column, 'ruleCategory');
      // column.dicData = getDicData(this.ruleType);
      this.$refs.crud.$refs.headerSearch.searchReset();
      this.$nextTick(() => {
        this.$structuralSplit();
      });
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        const query = Object.assign(params, this.query);
        const objectType = this.activeName === 'materialCategory' ? 'mes_part_category' : 'mes_part_master';
        const searchParams = this.filterEmptyValues(query);
        const res = await (this.activeName === 'materialCategory'
          ? getMaterialCategoryList(page.currentPage, page.pageSize, { ...searchParams })
          : getMaterialList(page.currentPage, page.pageSize, { ...searchParams }));
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    // setPageType(val) {
    //   this.$set(this.option, 'column', catagoryData);
    //   const path = val.fullPath;
    //   const type = path.charAt(path.length - 1);
    //   const pathMap = { 1: 'RECEIVE_RULE', 2: 'OUTBOUND_RULE', 3: 'INWAREHOUSE_MANAGE_RULE' };
    //   const column = this.findObject(this.option.column, 'ruleCategory');
    //   column.dicData = getDicData(pathMap[type]);
    //   this.ruleType = pathMap[type];
    //   this.onLoad(this.page);
    // },
    newKey() {
      this.timer = new Date().getTime();
    },
    filterEmptyValues(obj) {
      for (let key in obj) {
        if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
          delete obj[key];
        }
      }
      return obj;
    },
    queryPart(type) {
      if (this.activeName === 'materialData') {
        let page = {
          pageSize: 20,
          currentPage: 1,
          total: 1
        };
        this.$refs.transfertable.fifoControlPart = type;
        this.$refs.transfertable.getMarteData(page);
      }
    }
  }
};
</script>
<style lang="scss" scoped></style>
